package com.job.landlord;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.job.common.result.Result;
import com.job.common.result.ResultCodeEnum;
import com.job.landlord.service.SystemUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wx")
public class UserConcroller {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SystemUserService userService;


    @Value("${jwt.secret}")
    private String secretKey;
    String appid = "wx33ef80d71b7e9626";
    String secret = "dfa6fca14fa91e493e21f6a9977a2120";

    @GetMapping("getOpenId")
    public Result<String> getOpenId(@RequestParam(value = "code") String code) throws JsonProcessingException {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        String res = restTemplate.getForObject(url, String.class);
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(res, Map.class);
        String openId = (String) map.get("openid");
        log.debug("获取OpenId的响应：{}", map.get("openid"));

            return userService.wxLogin(openId);



    }


    @GetMapping("getcity")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> getcity() {
        ClientUserDetails userInfo = userService.getUserInfo();
        System.out.println(userInfo);
        return Result.ok("北京");
    }
    //继续发请求获取手机号


    @GetMapping("bind")
    public Result<String> bind(@RequestParam(value = "code") String code,
                               @RequestHeader(value = "token", required = false) String token) throws JsonProcessingException {

        boolean isValid = JWTUtil.verify(token, secretKey.getBytes());
        JWT jwt = JWTUtil.parseToken(token);

        String openId = (String) jwt.getPayload("openid");
        if (!isValid || openId == null) {
            return Result.fail(401, "token无效");
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;

        String res = restTemplate.getForObject(url, String.class);
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(res, Map.class);
        String access_token = (String) map.get("access_token");
        String url2 = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        //发送请求获取手机号
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        String codeStr = mapper.writeValueAsString(params);
        String res2 = restTemplate.postForObject(url2, codeStr, String.class);
        Map map2 = mapper.readValue(res2, Map.class);
        String phoneNumber = ((Map<String, String>) map2.get("phone_info")).get("phoneNumber");

        log.debug("手机号：{},{}", phoneNumber, openId);
        return userService.bind(openId, phoneNumber);

        //更新用户信息，通过手机号查询用户，


    }


}

